﻿using System;
using System.Threading;
using Instances.Contracts;
using Microsoft.HomeServer.SDK.Interop.v1;
using WhsFacebook.Net.Contracts;

namespace WhsFacebook.Whs.Service.Submitters
{
    public abstract class InfoSubmitter<T>
    {
        protected readonly log4net.ILog _log;
        private Timer _timer;
        private readonly object _submitLock = new object();

        public DateTime LastSubmit
        {
            get;
            private set;
        }

        public T LastInfo
        {
            get;
            private set;
        }

        private void OnTick(object state)
        {
            try
            {
                DoSubmit();
            }
            catch (Exception x)
            {
                _log.Warn("Failed to submit information", x);
            }
        }

        public void SubmitNow()
        {
            _log.Info("Submitting information manually...");

            try
            {
                DoSubmit();
            }
            catch (Exception x)
            {
                _log.Error("Failed to submit information manually", x);

                throw;
            }
        }

        private void DoSubmit()
        {
            lock (_submitLock)
            {
                try
                {
                    if (_log.IsDebugEnabled)
                        _log.Debug("Submit information...");

                    this.LastInfo = DoSubmitInternal();

                    this.LastSubmit = DateTime.Now;
                }
                catch (Exception e)
                {
                    _log.Error("Failed to check for update", e);

                    throw;
                }
            }
        }

        protected abstract T DoSubmitInternal();

        protected InfoSubmitter()
        {
            _log = log4net.LogManager.GetLogger(GetType());

            if (_log.IsDebugEnabled)
                _log.Debug("Creating submitter");

            try
            {
                this.LastSubmit = DateTime.MinValue;
	
                // initialize update check timer
                _timer = new Timer(
                    new TimerCallback(OnTick),
                    null,
                    1000,
                    (1000 * 60 * Properties.Settings.Default.SubmitInfoIntervalMinutes)
                    );
            }
            catch (Exception e)
            {
                _log.Fatal("Failed to create submitter", e);

                throw;
            }

        }
    }
}